//
//  ContactPersonViewController.m
//  HuaRun
//
//  Created by admin on 17/8/28.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "ContactPersonViewController.h"
#import "ContactPersonCell.h"
#import "ChooseContactPersonView.h"
#import "BaseDynamicTagView.h"
#import "Contact_ListModel.h"
#import "ConditionModel.h"
#import "ImageLabView.h"
#import "SearchView.h"
#import "Contact_DetailViewController.h"

@interface ContactPersonViewController ()

@property(nonatomic, strong) ChooseContactPersonView * choosePersonView;
//称谓数组
@property(nonatomic, strong) NSArray * salutationArray;
//标签数组
@property(nonatomic, strong) NSArray * cddCatagoryArray;
//选择的称谓
@property(nonatomic, copy)NSString * salutation ;
//选择的部门标签
@property(nonatomic, copy)NSString * category;
@end

@implementation ContactPersonViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = NSLocalizedString(@"contacts_list", nil);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[ContactPersonCell class] forCellReuseIdentifier:@"ContactPersonCell"];
    self.searchView.placeholderStr = NSLocalizedString(@"搜索联系人名称", nil);

    weakself(ws);
    [self nbRightImageName:@"screen" title:nil taget:self clickBlock:^(id result) {
        [ws selectMethod];
    }];
    
    [self.searchView.textField addTarget:self action:@selector(searchFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

    self.searchView.clickBlock = ^(id result) {
        [ws searchBtnMethod];
    };
    
    self.normalDZNEmptyDataSouce.reloadBlock = ^{
        [ws dataInit];
    };

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ContactPersonCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ContactPersonCell" forIndexPath:indexPath];
    cell.phoneBtn.hidden = NO;
    cell.emailBtn.hidden = NO;
    cell.personModel = self.dataArray[indexPath.row];

    cell.callPhoneBlock = ^(NSString *phoneNum) {
        [ToolHelper callWithPhoneNum:phoneNum];
    };

    cell.sendEmailBlock = ^(NSString *emailStr) {
        [ToolHelper openEamilWithEmailStr:emailStr];
    };

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    Contact_DetailViewController * meetingVC = [[Contact_DetailViewController alloc] init];
    meetingVC.hidesBottomBarWhenPushed = YES;
    Contact_ListModel * personModel = self.dataArray[indexPath.row];
    meetingVC.contactId = personModel.id;
    [self.navigationController pushViewController:meetingVC animated:YES];
}


- (void)dataInit {
    [super dataInit];
    
    [self searchMethod];
    
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
//        //子线程处理事件如：处理耗时操作、网络请求等
//        
        [self fetchConfitionalByType:@"salutation"];
        [self fetchConfitionalByType:@"cddCategory"];

//        dispatch_sync(dispatch_get_main_queue(), ^{
//            //主线程处理事件部分,刷新UI，将子线程得到的数据结果，展示到UI上
//            
//        });
//    });
}
- (void)layoutInit {
    
    weakself(ws);
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ws.view).offset(kMargin10);
        make.right.mas_equalTo(ws.view).offset(-kMargin10);
        make.top.mas_equalTo(ws.view).offset(0);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(ws.view);
        make.bottom.mas_equalTo(ws.view).offset(-48);
        make.top.mas_equalTo(ws.searchView.mas_bottom).offset(0);
    }];
    
}


-(void)methodBind {
    
    weakself(ws);
    [self.tableView headerRefresh:^{
        [ws refreshData];
    }];
    [self.searchView.textField addTarget:self action:@selector(recoverOriginDataMethod:)
                        forControlEvents:(UIControlEventEditingChanged)];

}

#pragma mark - method

- (void)recoverOriginDataMethod:(UITextField *)textField {
    if (textField.text.length == 0) {
        NSLog(@"恢复最初数据");
        [self searchMethod];
    }else {
        NSLog(@"准备搜索");
    }
}

//弹出高级筛选视图
- (void)selectMethod {
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    
    self.choosePersonView = [[ChooseContactPersonView alloc] initWithFrame:window.bounds];
    [window addSubview:self.choosePersonView];
    
    _choosePersonView.tagView.tagArray = self.salutationArray;
    
    _choosePersonView.departmentLabel.frame = CGRectMake(kMargin10,
                                                         CGRectGetMaxY(_choosePersonView.tagView.frame) + kMargin10 * 3, kChooseViewWidth, 20);
    _choosePersonView.buMenTagView.frame = CGRectMake(_choosePersonView.tagView.xj_x,
                                                      CGRectGetMaxY(_choosePersonView.tagView.frame) + CGRectGetHeight(_choosePersonView.departmentLabel.frame) + kMargin10 * 3,
                                                      _choosePersonView.tagView.xj_width,
                                                      _choosePersonView.tagView.xj_height);

    _choosePersonView.buMenTagView.tagArray = self.cddCatagoryArray;
    _choosePersonView.scrollBackView.contentSize = CGSizeMake(_choosePersonView.scrollBackView.xj_width,
                                                              CGRectGetMaxY(_choosePersonView.buMenTagView.frame)
                                                              + kMargin10);
    weakself(ws);
    
    [_choosePersonView.noteView addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        NSLog(@"取消");
        [ws.choosePersonView dismissSelfMethod];
    }];
    
    [_choosePersonView.resetView addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        NSLog(@"重置");
        [ws.choosePersonView.tagView resetSelectedConditional];
        [ws.choosePersonView.buMenTagView resetSelectedConditional];
    }];
    
    [_choosePersonView.sureView addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        NSLog(@"确定");
        [ws highSelectedMethod];
        
    }];
}


//获取筛选的条件
- (void)fetchConfitionalByType:(NSString *)type {
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kSelectConditionUrl];
    
    weakself(ws);
    NSDictionary * dic = @{@"type": type};
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            [ws showAlert:object[@"msg"] ? object[@"msg"] : @"" ];

            return;
        }
        NSArray * array = [NSArray yy_modelArrayWithClass:[ConditionModel class] json:object[@"obj"]];
        
        if ([type isEqualToString:@"salutation"]) {
            ws.salutationArray = array;
        }else if ([type isEqualToString:@"cddCategory"]) {
            ws.cddCatagoryArray = array;
        }
        
    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
    }];
}

//    联系人参数：orderBy，取值：name create modify，默认为name
- (void)searchMethod {
    [self.view endEditing:YES];
    
    NSString * keyword = [NSString isemptyStr:self.searchView.textField.text] ? @"" : self.searchView.textField.text;
    
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kContactListUrl];
    
    NSDictionary * dic = @{@"current": @(self.current),
                           @"size": @(self.size),
                           @"keyword": keyword,
                           @"salutation": [NSString showSpaceStringWithStr:_salutation],
                           @"category": [NSString showSpaceStringWithStr:_category],                           
                           @"orderBy": @"name"
                           };
    weakself(ws);

    [self showActivity:kLodingStr];

    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        [ws hideAllAlert];
        [ws.tableView endHeaderRefresh];
        
        if (![object[@"code"] isEqual: kSuccessCode]) {
            [ws showAlert:object[@"msg"] ? object[@"msg"] : @"" ];

            return;
        }
        NSArray * array = [NSArray yy_modelArrayWithClass:[Contact_ListModel class] json:object[@"list"]];

        ws.dataArray = ws.current == 1 ? array : [ws.dataArray arrayByAddingObjectsFromArray:array];
        [ws.tableView reloadData];
        
        if (array.count >= ws.size) {
            
            [ws.tableView footerRefresh:^{
                [ws loadMoreData];
            }];
        }else {
            [ws.tableView hiddenFooter];
        }
        
    } failure:^(NSError *error) {
        [ws hideAllAlert];

        //        NSLog(@"fail %@", error);
        [ws.tableView endHeaderRefresh];
        [ws showWithText:kNetworkError];
        [ws.normalDZNEmptyDataSouce setDznEmptyStatus:(DZNEmptyStatusFailure)];

    }];
    
}

- (void)refreshData {
    self.current = 1;
    self.category = @"";
    self.salutation = @"";
    self.searchView.textField.text = @"";
    
    [self searchMethod];
}

- (void)loadMoreData {
    self.current++;
    [self searchMethod];
}

//当搜索框内容为空时候，相当于执行一次刷新操作
- (void) searchFieldDidChange:(UITextField *)textField {
    if (textField.text.length == 0) {
        [self refreshData];
    }
}
//点击搜索按钮时， 页数置1， 高级筛选条件置空
- (void)searchBtnMethod {
    self.current = 1;
    self.category = @"";
    self.salutation = @"";

    [self searchMethod];
}

//高级筛选
- (void)highSelectedMethod{
    [self.view endEditing:YES];

    self.current = 1;
    self.salutation = [self.choosePersonView.tagView getSelectdConditional];
    self.category = [self.choosePersonView.buMenTagView getSelectdConditional];
    
    [self searchMethod];
    
    [self.choosePersonView dismissSelfMethod];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
